package com.study.spmongodb.wwj.juc.utils.executors;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author study
 * @version 1.0
 * @date 2020/12/15 14:10
 */
public class ThreadPoolExecutorTask {

    public static void main(String[] args) throws InterruptedException {
        final ThreadPoolExecutor poolExecutor = buildThreadPoolExecutor();
        IntStream.range(0, 20).boxed().forEach(i -> {
            poolExecutor.execute(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    System.out.println(Thread.currentThread().getName() + " " + i + " finished done");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        });
        //非阻塞
        poolExecutor.shutdown();
        poolExecutor.awaitTermination(1, TimeUnit.MICROSECONDS);
        System.out.println("======================");
    }

    public static ThreadPoolExecutor buildThreadPoolExecutor() {
        final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                10, 20, 30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1),
                r -> {
                    final Thread thread = new Thread(r);
                    return thread;
                }, new ThreadPoolExecutor.AbortPolicy()
        );
        System.out.println("buildThreadPoolExecutor success");
        return poolExecutor;
    }
}
